package com.pet_service.config;

import cn.hutool.json.JSONUtil;
import com.pet_service.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义退出登录处理器
 */
@Slf4j
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        // 记录退出登录信息，包括用户身份
        if (authentication != null && authentication.getPrincipal() != null) {
            log.info("用户 {} 退出登录成功", authentication.getPrincipal());
        } else {
            log.info("匿名用户退出登录");
        }
        //封装传递给前端vue项目的对象
        Result r =Result.ok(200,"退出成功");
        //将对象转换成json格式字符串
        String jsonStr = JSONUtil.toJsonStr(r);
        //使用字符输出流传递数据
        response.getWriter().write(jsonStr);
    }
}
